package com.syqc.videos.players

import android.content.Context
import android.media.AudioManager
import android.util.AttributeSet
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYVideoViewBridge
import com.syqc.videos.SimpleVideoCallBack
import com.syqc.videos.videomanager.IPlayerListener
import com.syqc.videos.videomanager.PlayerManager

class AudioPlayer : StandardGSYVideoPlayer, IPlayerListener {

    constructor(context: Context?, fullFlag: Boolean?) : super(context, fullFlag)
    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    fun getKey(): String {
        return "audio_key_player$mPlayPosition"
    }

    override fun init(context: Context?) {
        super.init(context)
        isRotateViewAuto = true //是否开启制动旋转
        setIsTouchWigetFull(false)
        isLockLand = true
        val key = getKey()
        PlayerManager.getCustomManager(key).setNeedMute(key, false)
        onAudioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange: Int ->
            when (focusChange) {
                AudioManager.AUDIOFOCUS_GAIN -> {
                }
                AudioManager.AUDIOFOCUS_LOSS -> {
                }
                AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
                }
                AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
                }
            }
        }
        setVideoAllCallBack(object : SimpleVideoCallBack {
            override fun onPrepared(url: String?, vararg objects: Any?) {
                super.onPrepared(url, *objects)
                callback?.success()
            }

            override fun onPlayError(url: String?, vararg objects: Any?) {
                super.onPlayError(url, *objects)
                callback?.failure()
            }
        })
    }

    override fun getGSYVideoManager(): GSYVideoViewBridge {
        val manager = PlayerManager.getCustomManager(getKey())
        manager.initContext(context.applicationContext)
        manager.setVoiceListener(this)
        return manager
    }

    public override fun releaseVideos() {
        PlayerManager.releaseAllVideos(getKey())
    }


    private var callback: AudioCallBack? = null
    fun setAudioCallBack(back: AudioCallBack) {
        callback = back
    }

    override fun onMuteChange(isNeedMute: Boolean) {
        if (isNeedMute) {
            callback?.finishTalk()
        }
    }

    override fun onPassChange(isChoose: Boolean) {

    }
}

interface AudioCallBack {
    fun finishTalk()
    fun success()
    fun failure()
}